package ua.org.nuos.wclientgui.panels;

import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.Button;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.PasswordTextField;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.model.PropertyModel;
import ua.org.nuos.sdms.middle.entity.enums.Role;
import ua.org.nuos.sdms.middle.service.AuthenticationLocal;
import ua.org.nuos.wclientgui.pages.MainPage;

import javax.ejb.EJB;
import javax.servlet.ServletException;

/**
 * Created with IntelliJ IDEA.
 * User: dio
 * Date: 9/16/12
 * Time: 2:58 PM
 * To change this template use File | Settings | File Templates.
 */
public class LoginPanel extends BasePanel {

    @EJB(name = "ejb/AuthenticationLocal")
    private AuthenticationLocal authenticationBean;

    private TextField loginField, passwordField;
    private String login = "", password = "", out = "";

    public LoginPanel(String id) {
        super(id);

        Label label = new Label("outLabelId", new PropertyModel<String>(this, "out"));

        loginField = new TextField("loginId", new PropertyModel<String>(this, "login"));
        passwordField = new PasswordTextField("passwordId", new PropertyModel<String>(this, "password"));
        Form loginForm = new Form("loginFormId");
        loginForm.add(loginField);
        loginForm.add(passwordField);
        loginForm.add(new Button("submitId") {

            @Override
            public void onSubmit() {
                try {
                    getApp().getRequest().login(login, password);
                    String roleName = "nothing";
                    for (Role role : Role.values()) {
                        if (authenticationBean.isUserInRole(role.toString())) {
                            roleName = role.toString();
                            break;
                        }
                    }
                    out = "success login as " + roleName;
                    setResponsePage(new MainPage());
                } catch (ServletException e) {
                    out = "fail login";
                    e.printStackTrace();
                }
            }
        });
//        loginForm.add(new IFormValidator() {
//            @Override
//            public FormComponent<?>[] getDependentFormComponents() {
//                return new FormComponent<?>[0];
//            }
//
//            @Override
//            public void validate(Form<?> form) {
//            }
//        });

        add(loginForm);
        add(label);
    }
}
